package org.dromara.workflow.rocketmq.leave;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import com.cloud.rocketmq.base.entity.CloudMessage;
import com.cloud.rocketmq.spring.annotation.ConsumeTopic;
import com.cloud.rocketmq.spring.core.TopicListener;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.enums.BusinessStatusEnum;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.tenant.helper.TenantHelper;
import org.dromara.workflow.api.event.ProcessEvent;
import org.dromara.workflow.domain.TestLeave;
import org.dromara.workflow.mapper.TestLeaveMapper;

import java.util.Map;

import static org.dromara.common.core.constant.RocketMQConstants.FlowTopic.FLOW_PROCESS_TAG_NAME;
import static org.dromara.common.core.constant.RocketMQConstants.FlowTopic.FLOW_PROCESS_TOPIC_NAME;

/**
 * 总体流程监听(例如: 草稿，撤销，退回，作废，终止，已完成，单任务完成等)
 * 正常使用只需#processEvent.flowCode=='leave1'
 * 示例为了方便则使用startsWith匹配了全部示例key
 */
@Slf4j
@ConsumeTopic(topic = FLOW_PROCESS_TOPIC_NAME, eventCode = FLOW_PROCESS_TAG_NAME, log = true)
@RequiredArgsConstructor
public class ProcessListener implements TopicListener<ProcessEvent> {

    private final TestLeaveMapper testLeaveMapper;

    @Override
    public void onMessage(CloudMessage<ProcessEvent> processMessage) {
        log.info("总体流程监听消息:{}", JsonUtils.toJsonString(processMessage));
        ProcessEvent processEvent = processMessage.getPayload();
        if (processEvent.getFlowCode().startsWith("leave")) {
            TenantHelper.dynamic(processEvent.getTenantId(), () -> {
                log.info("当前任务执行了{}", processEvent);
                TestLeave testLeave = testLeaveMapper.selectById(Long.valueOf(processEvent.getBusinessId()));
                testLeave.setStatus(processEvent.getStatus());
                // 用于例如审批附件 审批意见等 存储到业务表内 自行根据业务实现存储流程
                Map<String, Object> params = processEvent.getParams();
                if (MapUtil.isNotEmpty(params)) {
                    // 历史任务扩展(通常为附件)
                    String hisTaskExt = Convert.toStr(params.get("hisTaskExt"));
                    // 办理人
                    String handler = Convert.toStr(params.get("handler"));
                    // 办理意见
                    String message = Convert.toStr(params.get("message"));
                }
                if (processEvent.getSubmit()) {
                    testLeave.setStatus(BusinessStatusEnum.WAITING.getStatus());
                }
                testLeaveMapper.updateById(testLeave);
            });
        }
    }

}
